<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>{{ isLoginMode ? '登录' : '注册新账号' }}</h2>
        <button class="toggle-mode" @click="toggleMode">
          {{ isLoginMode ? '注册账号' : '已有账号，去登录' }}
        </button>
      </div>

      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label>手机号</label>
          <input type="tel" v-model="form.phone" placeholder="请输入手机号" maxlength="11" required />
        </div>

        <div class="form-group">
          <label>密码</label>
          <input type="password" v-model="form.password" placeholder="请输入密码" minlength="6" required />
        </div>

        <div class="form-group" v-if="!isLoginMode">
          <label>验证码</label>
          <div class="verify-code">
            <input type="text" v-model="form.code" placeholder="请输入验证码" maxlength="6" required />
            <button type="button" :disabled="countdown > 0" @click="sendCode">
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </button>
          </div>
        </div>

        <button type="submit" @click="isLoginMode ? handleLogin() : handleRegister()" class="submit-btn">
          {{ isLoginMode ? '登录' : '注册' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getYzm, verificationYzm } from '../../api/yzm.js'
import { Login } from '../../api/login.js'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/modules/user.js'


//初始化实例

const route = useRouter()
const isLoginMode = ref(true)
const countdown = ref(0)
const UserStore = useUserStore()
const fullscreenLoading = ref(false)


const form = reactive({
  phone: '15222767758',
  password: '15222767758',
  code: ''
})

const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  // 重置表单
  form.phone = '15222767758'
  form.password = '15222767758'
  form.code = ''
}

const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    alert('请输入正确的手机号')
    return
  }
  //发送验证码
  try {
    const res = await getYzm(form.phone)
    console.log(res)
    if (res.code === 10000) {
      ElMessage({
        showClose: true,
        message: '发送成功',
        type: 'success',
      })
    } else {
      ElMessage({
        showClose: true,
        message: '发送失败',
        type: 'error',
      })
    }
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }
  catch {
    alert('验证码发送失败，请稍后再试')
  }
}

const handleSubmit = () => {
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    alert('请输入正确的手机号')
    return
  }

  if (form.password.length < 6) {
    alert('密码至少6位')
    return
  }
  // 这里可以替换为实际的API调用
  if (isLoginMode.value) {

  } else {
    console.log('注册信息:', {
      phone: form.phone,
      password: form.password,
      code: form.code
    })
    toggleMode()
  }
}

//注册
const handleRegister = async () => {
  const res = await verificationYzm({
    phone: form.phone,
    password: form.password,
    code: form.code
  })
  // console.log(res)
  if (res.code === 10000) {
    ElMessage({
      showClose: true,
      message: '注册成功',
      type: 'success',
    })
  } else {
    ElMessage({
      showClose: true,
      message: '注册失败',
      type: 'error',
    })
  }
}

//登录
const handleLogin = async () => {
  //loading加载状态
    const loading = ElLoading.service({
      lock: true,
      text: 'Loading',
      background: 'rgba(0, 0, 0, 0.7)',
    })
  try {
    const res = await Login({
      phone: form.phone,
      password: form.password
    })
    if (res.code === 10000) {
      const ADMIN_TOKEN = res.data.token
      localStorage.setItem('ADMIN_TOKEN', ADMIN_TOKEN)
      localStorage.setItem('ADMIN_USER', JSON.stringify(res.data.userInfo))
      UserStore.setUserInfo(res.data.userInfo)
      ElMessage({
        showClose: true,
        message: '登录成功',
        type: 'success',
      })
      //等待跳转操作完成后再继续执行后面的代码”。
      await route.replace({ path: '/' })
    }
    // console.log(res)
  }
  finally {
    loading.close()
  }

}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: 'Arial', sans-serif;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.login-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin: 0;
}

.toggle-mode {
  background: none;
  border: none;
  color: #667eea;
  cursor: pointer;
  font-size: 14px;
  text-decoration: underline;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: bold;
}

input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  box-sizing: border-box;
}

input:focus {
  outline: none;
  border-color: #667eea;
}

.verify-code {
  display: flex;
  gap: 10px;
}

.verify-code input {
  flex: 1;
}

.verify-code button {
  width: 120px;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
}

.verify-code button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.submit-btn:hover {
  background: #5a6fd8;
}
</style>